package kr.saeildamil.androidstudy_second.multimedia;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;

import kr.saeildamil.androidstudy_second.R;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class PlayAudio extends Activity {
	ArrayList<String> mList;
	int mIdx;
	MediaPlayer mPlayer;
	TextView mFileName;
	SeekBar mProgress;
	boolean wasPlaying;
	String mSdPath;
	Button mPlayBtn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch33_playaudio);
		
		mList = new ArrayList<String>();
		mPlayer = new MediaPlayer();
		
		//SD카드 없을 시  에러 처리
		String ext = Environment.getExternalStorageState();
		if(!ext.equalsIgnoreCase(Environment.MEDIA_MOUNTED)){
			Toast.makeText(this, "SD 카드가 필요", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		
		//SD카드 루트의  MP3 파일 목록을 구한다.
		mSdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		File sdRoot =  new File(mSdPath);
		FilenameFilter filter =  new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				return filename.endsWith(".mp3");
			}
		};
		
		String[] mpList = sdRoot.list(filter);
		if(mpList.length == 0){
			Toast.makeText(this, "재생할 파일이 없음", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		for(String str:mpList){
			//Toast.makeText(this, mSdPath+"/"+str, Toast.LENGTH_LONG).show();
			mList.add(mSdPath+"/"+str);
		}
		
		//버튼들의 클릭 리스너 등록
		mFileName = (TextView) findViewById(R.id.filename);
		mPlayBtn = (Button) findViewById(R.id.play);
		mProgress = (SeekBar) findViewById(R.id.progress);
		
		//완료 리스너, 시크바 변경 리스너 등록
		mPlayer.setOnCompletionListener(mOnComplete);
		mPlayer.setOnSeekCompleteListener(mOnSeekComplete);
		mPlayer.setOnErrorListener(mOnError);
		
		mProgress.setOnSeekBarChangeListener(mOnSeek);
		mProgressHander.sendEmptyMessageDelayed(0, 200);
	
		//첫 곡 읽기 및 준비
		if  (!loadMedia(mIdx)){
			Toast.makeText(this, "파일을 읽을 수 없음", Toast.LENGTH_LONG).show();
			finish();
		}
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
		//재생 및 일시 정지
		case R.id.play:
			if (!mPlayer.isPlaying()){
				mPlayer.start();
				mPlayBtn.setText("Pause");
			}else{
				mPlayer.pause();
				mPlayBtn.setText("Play");
			}
			break;
		
		//재생 정지. 재시작을 위해 미리 준비해 놓는다.
		case R.id.stop:
			mPlayer.stop();
			mPlayBtn.setText("Play");
			mProgress.setProgress(0);
			try {
				mPlayer.prepare();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case R.id.prev:
		case R.id.next:
			boolean wasPlaying = mPlayer.isPlaying();
			
			if (v.getId()==R.id.prev){
				mIdx = (mIdx == 0? mList.size()-1:mIdx-1);
			}else{
				mIdx = (mIdx == mList.size()-1? 0: mIdx+1);
			}
			mPlayer.reset();
			loadMedia(mIdx);
			
			//이전에 재생 중이었으면 다음 곡 바로 재생
			if (wasPlaying){
				mPlayer.start();
				mPlayBtn.setText("Pause");
			}
			break;
		}
	}
	
	protected void onPause() {
		super.onPause();
		if (mPlayer!=null){
			mPlayer.release();
			mPlayer = null;
		}
	}

	MediaPlayer.OnErrorListener mOnError = new OnErrorListener() {
		public boolean onError(MediaPlayer mp, int what, int extra) {
			String err = "OnError occured. what = " + what + " ,extra " + extra;
			Toast.makeText(PlayAudio.this, err, Toast.LENGTH_LONG).show();
			return false;
		}
	};

	Handler mProgressHander = new Handler(){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (mPlayer==null) return;
			if (mPlayer.isPlaying()){
				mProgress.setProgress(mPlayer.getCurrentPosition());
			}
			mProgressHander.sendEmptyMessageDelayed(0, 200);
		}
	};
	
	OnSeekBarChangeListener mOnSeek = new OnSeekBarChangeListener() {
		public void onStopTrackingTouch(SeekBar seekBar) {
			
		}
		
		public void onStartTrackingTouch(SeekBar seekBar) {
			wasPlaying = mPlayer.isPlaying();
			if (wasPlaying){
				mPlayer.pause();
			}
		}
		
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser){
				mPlayer.seekTo(progress);
			}
		}
	};
	
	OnSeekCompleteListener mOnSeekComplete = new OnSeekCompleteListener() {
		public void onSeekComplete(MediaPlayer mp) {
			if (wasPlaying){
				mPlayer.start();
			}
		}
	};
	
	OnCompletionListener mOnComplete = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mp) {
			//전곡이 다 재생되면 첫곡으로 그렇지 않으면 다음곡으로
			mIdx = (mIdx == mList.size()-1?0:mIdx+1);
			mPlayer.reset();//곡이 바뀌므로 reset()호출
			loadMedia(mIdx);
			mPlayer.start();
		}
	};

	boolean loadMedia(int mIdx) {
		try {
			mPlayer.setDataSource(mList.get(mIdx));
			mPlayer.prepare();
		} catch (IllegalArgumentException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		} catch (SecurityException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		} catch (IllegalStateException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
		
		mFileName.setText("파일 : " + mList.get(mIdx));
		mProgress.setMax(mPlayer.getDuration());
		return true;
	}
}














